# -*- coding: utf-8 -*-

from bottle import route, run, get, post, request
from setproctitle import setproctitle
from DB import DB
from Users import Users
import json


setproctitle('emarkd')

# init section
users = Users()


def hint_message(message = '', **kw):
    if message == '':
        o = { 'success': True }
    else:
        o = { 'success': False, 'message': message }

    for k in kw:
        o[k] = kw[k]

    return json.dumps(o)

def web_param(request, name):
    if name in request.query:
        return request.query[name]

    return ''

def web_auth(request):
    userid = web_param(request, 'uid')
    password = web_param(request, 'pwd')

    if userid == '' or password == '':
        return False

    db = DB()
    row = db.Fetch('SELECT * FROM Auth WHERE Id = %s AND Password = %s AND Role = %s', (userid, password, 'client'))
    db.Close()

    return row != None

@route('/login')
def web_login():
    if web_auth(request):
        users.login(web_param(request, 'uid'))
        return hint_message()

    return hint_message('auth failed!')

@route('/logout')
def web_logout():
    if web_auth(request):
        users.logout(web_param(request, 'uid'))
        return hint_message()

    return hint_message('auth failed!')

@route('/list')
def web_list():
    o = []
    for uid in users.users:
        task_id, task_keyword, task_price, task_status, task_count = users.getInfo(uid)
        o.append({'uid': uid, 'task_id': task_id, 'task_keyword': task_keyword, 'task_price': task_price, 'task_status': task_status, 'task_count': task_count})

    return json.dumps(o)

@route('/info')
def web_info():
    if not web_auth(request):
        return json.dumps({})

    uid = web_param(request, 'uid')
    task_id, task_keyword, task_price, task_status, task_count = users.getInfo(uid)
    o = {'task_id': task_id, 'task_keyword': task_keyword, 'task_price': task_price, 'task_status': task_status, 'task_count': task_count}

    return json.dumps(o)

@route('/start')
def web_start():
    keyword = web_param(request, 'keyword')
    price = web_param(request, 'price')

    try:
        if keyword == '' or price == '':
            raise Exception('invalid parameter')

        price = float(price)
        if price <= 0.001:
            raise Exception('invalid parameter')
    except:
        return hint_message('invalid parameter!')

    if web_auth(request):
        uid = web_param(request, 'uid')
        task_id = users.start(uid, keyword, price)
        if task_id != '':
            return hint_message()
        else:
            return hint_message('start failed!')

    return hint_message('auth failed!')

@route('/stop')
def web_stop():
    if not web_auth(request):
        return hint_message('auth failed!')

    uid = web_param(request, 'uid')
    users.stop(uid)

    return hint_message()

@route('/clear')
def web_clear():
    if not web_auth(request):
        return hint_message('auth failed!')

    uid = web_param(request, 'uid')
    users.clear(uid)

    return hint_message()

@route('/data')
def web_data():
    if not web_auth(request):
        return json.dumps([])

    uid = web_param(request, 'uid')

    try:
        offset = int(web_param(request, 'offset'))
        limit = int(web_param(request, 'limit'))

        if offset < 0 or limit <= 0:
            raise Exception('invalid parameter')
    except:
        return json.dumps([])
        
    data = users.data(uid, offset, limit)

    return json.dumps(data)


run(host = '0.0.0.0', port = 9000, quiet = True)

